<template>
  <!-- 首页统计-echarts -->
  <div class="dashboard-statistics" v-loading="loading">
    <div class="l-tab">
      <!-- Tab 切换 -->
      <div
        class="tab"
        :class="{ isactive: tabsState.activeName === item.id }"
        v-for="item in tabs"
        :key="item.id"
        @click="setActive('activeName', item.id + '')"
      >
        {{ item.name }}
      </div>
    </div>

    <!-- 运营统计 -->
    <div class="stat-operation" v-if="tabsState.activeName === 'operate'">
      <div class="chart-container">
        <div class="chart-title">访问量</div>
        <div class="chart-datas">
          <div class="chart-datas-item">
            <div>昨日</div>
            <p>{{ volumeEcharts.yesterday }}</p>
          </div>
          <div class="chart-datas-item">
            <div>本月</div>
            <p>{{ volumeEcharts.month }}</p>
          </div>
          <div class="chart-datas-item">
            <div>本年</div>
            <p>{{ volumeEcharts.year }}</p>
          </div>
        </div>
        <div class="chart-row">
          <span class="chart-unit">人</span>
          <!-- 本月/本年切换 -->
          <div class="chart-switch">
            <span
              :class="{ active: tabsState.visitTab === 'year' }"
              @click="setActive('visitTab', 'year')"
            >
              本年
            </span>
            <span
              :class="{ active: tabsState.visitTab === 'month' }"
              @click="setActive('visitTab', 'month')"
            >
              本月
            </span>
          </div>
        </div>
        <div class="echarts">
          <EChartWrapper :type="'line'" :options="volumeChartOptions" />
        </div>
      </div>

      <div class="split-line"></div>
      <div class="chart-container">
        <el-tabs
          v-model="tabsState.tabActiveName"
          class="tabs"
          @tab-change="setActive('tabActiveName', tabsState.tabActiveName)"
          @tab-click="(e:any) => (statType = e.index)"
        >
          <el-tab-pane
            :label="item.name"
            :name="item.name"
            v-for="item in echartsTabs"
            :key="item.id"
            :class="{ tabsActive: tabsState.tabActiveName === item.name }"
          >
            <div class="chart-datas">
              <div class="chart-datas-item">
                <div>昨日</div>
                <p>{{ userEcharts.yesterday }}</p>
              </div>
              <div class="chart-datas-item">
                <div>本月</div>
                <p>{{ userEcharts.month }}</p>
              </div>
              <div class="chart-datas-item">
                <div>本年</div>
                <p>{{ userEcharts.year }}</p>
              </div>
              <div class="chart-datas-item">
                <div>全部</div>
                <p>{{ userEcharts.total }}</p>
              </div>
            </div>
            <div class="chart-row">
              <span class="chart-unit">人</span>
              <div class="chart-switch">
                <span
                  :class="{ active: tabsState.userTab === 'year' }"
                  @click="setActive('userTab', 'year')"
                >
                  本年
                </span>
                <span
                  :class="{ active: tabsState.userTab === 'month' }"
                  @click="setActive('userTab', 'month')"
                >
                  本月
                </span>
              </div>
            </div>
            <div class="echarts">
              <EChartWrapper :type="'line'" :options="userChartOptions" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 工单 -->
    <div v-else class="statistics-workorder">
      <!-- 头部 -->
      <div class="statistics-workorder-header">
        <div class="statistics-workorder-title">
          <span>我的工单 ({{ total }})</span>
          <span
            class="all"
            @click="() => router.push('/serviceCenter/submitWorkOrder')"
          >
            全部工单
          </span>
        </div>
        <el-button
          :icon="Plus"
          class="medium"
          @click="() => router.push('/serviceCenter/submitWorkOrder')"
        >
          发工单
        </el-button>
      </div>

      <!-- 工单列表 -->
      <div class="workorder-list">
        <div
          v-for="(item, index) in workerList"
          :key="index"
          class="workorder-list-item"
        >
          <div class="workorder-title">
            <div class="f14">{{ WORKERTYPE[item.type] }}</div>
            <div class="f12">{{ item.create_time }}</div>
          </div>
          <div class="workorder-content">
            <div class="workorder-html">{{ item.content }}</div>
            <div
              :class="['workorder-status', 'workorder-status-' + item.status]"
            >
              {{ WORKERSTATUS[item.status] }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import dashboard from '@/modules';
const {
  getWorkListApi,
  WORKERSTATUS,
  WORKERTYPE,
  getUserEchartsApi,
  getVolumeEchartsApi,
} = dashboard;
import { ref, PropType, onMounted, computed } from 'vue';
import { TabItem, SeriesData } from '@/types/dashboard/index';
import EChartWrapper from '@/components/ECharts/index.vue';
import * as echarts from 'echarts';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { formatNumber } from '@/utils';

const router = useRouter();

// 接收 props
defineProps({
  tabs: {
    type: Array as PropType<TabItem[]>, // tabs 的类型是 TabItem 数组
    required: true,
  },
  echartsTabs: {
    type: Array as PropType<TabItem[]>, // echartsTabs 的类型也是 TabItem 数组
    required: true,
  },
});

const statType = ref('0'); // 请求的统计类型
const loading = ref(false); // 请求loading状态

type Worker = {
  type: string;
  create_time: string;
  status: string;
  content: string;
};

// 工单数据类型
type WorkerList = Worker[] | null;
const workerList = ref<WorkerList>([]); // 默认值为空数组
const total = ref(0); // 工单总数

// 访问量统计数据
const volumeEcharts = ref<{
  month: number;
  total: number;
  yesterday: number;
  year: number;
  seriesData: SeriesData;
}>({
  month: 0,
  total: 0,
  yesterday: 0,
  year: 0,
  seriesData: [],
});

// 用户统计数据
const userEcharts = ref<{
  month: number;
  total: number;
  yesterday: number;
  year: number;
  seriesData: SeriesData;
}>({
  month: 0,
  total: 0,
  yesterday: 0,
  year: 0,
  seriesData: [],
});

// 选项卡状态
const tabsState = ref({
  visitTab: 'year', // 访问量的本月/本年切换
  userTab: 'year', // 用户统计的本月/本年切换
  activeName: 'operate', // tab切换的名称
  tabActiveName: '注册用户', // 注册用户-VIP用户-一对一用户
});

// 访问量Echarts配置
const volumeChartOptions = computed(() =>
  getChartOptions(
    volumeEcharts.value.seriesData,
    tabsState.value.visitTab,
    false
  )
);

// 用户统计Echarts配置
const userChartOptions = computed(() =>
  getChartOptions(userEcharts.value.seriesData, tabsState.value.userTab, true)
);
// 本年本月-左/右侧选项卡
const setActive = (key: keyof typeof tabsState.value, value: string) => {
  loading.value = true;
  tabsState.value[key] = value;
  getData(key);
};
// Echarts 配置通用函数
const getChartOptions = (data: SeriesData, tabKey: string, isUser: boolean) => {
  return {
    xAxis: {
      type: 'category',
      data:
        tabKey === 'year'
          ? data[0]?.map((item: any) => `${item.month}月`) || []
          : data[0]?.map((item: any) => `${item.month}-${item.day}`) || [],
      axisTick: { show: false },
      axisLine: { lineStyle: { color: 'rgb(229,230,235)', width: 2 } },
      axisLabel: { formatter: '{value}' },
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any[]) {
        const axisLabel = params[0]?.axisValueLabel || '--';
        const tooltipContent = params
          .map((item) => {
            const data = item.data;
            return `
              <p>${item.seriesName}年${isUser ? '注册' : '访问'}人数: <b>${data.register}</b> 人</p>
              <p>同比去年: <b>${data.growth}</b> </p>
              <p>增长率: <b>${data.growthRate}</b></p>
            `;
          })
          .join('');
        return `<p><b>${axisLabel}</b></p>${tooltipContent}`;
      },
    },
    yAxis: { type: 'value' },
    series: data.map((yearArr, index) => ({
      name: yearArr[0]?.year,
      type: 'line',
      smooth: true,
      data: yearArr.map((item) => ({
        value: item.register,
        ...item,
      })),
      itemStyle: {
        color: index === 0 ? '#1c5dff' : '#dfe9ff',
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color:
              index === 0
                ? 'rgba(28, 93, 255, 0.5)'
                : 'rgba(223, 233, 255, 0.5)',
          },
          { offset: 1, color: 'rgba(28, 93, 255, 0)' },
        ]),
      },
    })),
  };
};
// 获取对应类型的数据
const getData = async (key: string) => {
  if (tabsState.value.activeName == 'operate') {
    if (['tabActiveName', 'userTab'].includes(key)) {
      getUserEcharts();
    } else {
      getVolumeEcharts();
    }
  } else {
    resetTabsState();
    getWorkerData();
  }
  loading.value = false;
};
// 切换右侧用户tab充值数据
const resetTabsState = () => {
  tabsState.value.visitTab = 'year';
  tabsState.value.userTab = 'year';
  tabsState.value.tabActiveName = '注册用户';
};
// 获取工单数据
const getWorkerData = async () => {
  const { data } = await getWorkListApi({ page: 1, pageSize: 4 });
  if (data.data.length) {
    workerList.value = data.data;
    total.value = data.total;
  }
};
// 获取用户统计
const getUserEcharts = async () => {
  const { data } = await getUserEchartsApi({
    statType: statType.value,
    type: tabsState.value.userTab,
  });
  userEcharts.value = {
    month: formatNumber(data.total.month),
    total: formatNumber(data.total.total),
    yesterday: formatNumber(data.total.yesterday),
    year: formatNumber(data.total.year),
    seriesData: data.data,
  };
};
// 获取访问量统计
const getVolumeEcharts = async () => {
  const { data } = await getVolumeEchartsApi({
    statType: 0,
    type: tabsState.value.visitTab,
  });
  volumeEcharts.value = {
    month: formatNumber(data.total.month),
    total: formatNumber(data.total.total),
    yesterday: formatNumber(data.total.yesterday),
    year: formatNumber(data.total.year),
    seriesData: data.data,
  };
};

onMounted(() => {
  getVolumeEcharts();
  getUserEcharts();
});
</script>

<style lang="scss" scoped src="./index.scss"></style>
